package com.topvision.myviewtest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import com.topvision.myviewtest.homekey.HomeKeyLocker;
import com.topvision.myviewtest.utils.ToastUtils;

public class HomeActivity extends AppCompatActivity {

    private int[] mRes = {R.drawable.timg_1,R.drawable.timg_2, R.drawable.timg_3, R.drawable.timg_2, R.drawable.timg_3};
    private VideoDeviceReceiver mReceiver;
    public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000; //需要自己定义标志
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);//关键代码
//        registerMyReceiver();
    }

    private void registerMyReceiver() {
        mReceiver = new VideoDeviceReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(mReceiver, intentFilter);
    }

    private void unRegisterMyReceiver() {
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }

    public void click(View view) {
        HomeKeyLocker homeKeyLocker = new HomeKeyLocker();
        homeKeyLocker.lock(this);
        ToastUtils.showToast(this,"搜索");
    }


    class VideoDeviceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action){
                case Intent.ACTION_CLOSE_SYSTEM_DIALOGS:
                    String reason = intent.getStringExtra("reason");
                    if(TextUtils.equals(reason, "homekey")){
                        ToastUtils.showToast(context, "点击了Home键");
                    }
                    abortBroadcast();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                ToastUtils.showToast(HomeActivity.this, "Menu键点击");
                break;

            case KeyEvent.KEYCODE_BACK:
                ToastUtils.showToast(HomeActivity.this, "Back键点击");
                break;
            case KeyEvent. KEYCODE_HOME:
                ToastUtils.showToast(HomeActivity.this, "Home键点击");
                return true;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterMyReceiver();
    }
}
